//
//  FMFileListViewController.m
//  WeEsion
//
//  Created by reylen on 15/11/30.
//  Copyright © 2015年 fdauto. All rights reserved.
//

#import "FMFileListViewController.h"
#import "UIImage+Color.h"
#import "FMSQLiteViewController.h"
#import "FMUtils.h"
#import "FMTxtViewController.h"
#import "PublicUtils.h"
#import "FMImageViewController.h"

@interface FMFileListViewController ()<UIAlertViewDelegate>

@property (copy, nonatomic) NSArray* fileList;
@property (copy, nonatomic) NSString* basePath;
@property (copy, nonatomic) NSString* childPath;

@end

@implementation FMFileListViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    self.title = @"文件管理";
    UIButton* button = [[UIButton alloc]init];
    button.exclusiveTouch = NO;
    button.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    
    [button setBackgroundImage:[[UIImage imageNamed:@"em_bar_back.png"] stretchableImageWithLeftCapWidth:31 topCapHeight:1] forState:UIControlStateNormal];
    if ([[UIDevice currentDevice].systemVersion floatValue] < 6.0) {
        [button setBackgroundImage:[[UIImage imageNamed:@"em_bar_back.png"] stretchableImageWithLeftCapWidth:31 topCapHeight:1] forState:UIControlStateHighlighted];
    }
    
    
    button.frame = CGRectMake(0, 0, 70, 30);
    
    [button addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem* back = [[UIBarButtonItem alloc] initWithCustomView:button];
    UIBarButtonItem* close = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStyleDone target:self action:@selector(cancel:)];
    self.navigationItem.leftBarButtonItems = @[back,close];
    
    NSString* docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    self.basePath = [docPath stringByDeletingLastPathComponent];
    
    self.fileList = @[@{@"title":@"Documents",@"isDir":@(YES)},@{@"title":@"Library",@"isDir":@(YES)}];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)back:(id)sender {
    
    if (!_childPath || _childPath.length == 0) {
        
        [self cancel:nil];
        
        return;
    }
    
    self.childPath = [_childPath stringByDeletingLastPathComponent];
    [self resetFileList];
    
}
- (IBAction)cancel:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void) resetFileList {
    
    
    if (!_childPath || _childPath.length == 0) {
        self.fileList = @[@{@"title":@"Documents",@"isDir":@(YES)},@{@"title":@"Library",@"isDir":@(YES)}];
        [self.tableView reloadData];
        return;
    }
    
    NSFileManager* fileManager = [NSFileManager defaultManager];
    
    NSString* path = [self.basePath stringByAppendingPathComponent:self.childPath];
    NSArray*content = [fileManager contentsOfDirectoryAtPath:path error:nil];
    
    NSMutableArray* listArray = [NSMutableArray arrayWithCapacity:content.count];
    
    for (NSString* node in content) {
        NSString*_path = [path stringByAppendingPathComponent:node];
        BOOL isDir;
        [fileManager fileExistsAtPath:_path isDirectory:&isDir];
        
        NSMutableDictionary* info = [NSMutableDictionary dictionary];
        
        [info setObject:node forKey:@"title"];
        [info setObject:@(isDir) forKey:@"isDir"];
        
        if (!isDir) {
            long long fileSize = [self fileSizeAtPath:_path];
            [info setObject:@(fileSize) forKey:@"size"];
        }
        else
        {
            long long fileSize = [self directorSizeAtPath:_path];
            [info setObject:@(fileSize) forKey:@"size"];
        }
        
        [listArray addObject:info];
    }
    
    self.fileList = listArray;
    
    [self.tableView reloadData];
    
}

- (long long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

- (long long) directorSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        NSArray* childs = [manager subpathsAtPath:filePath];
        NSLog(@"%@",childs);
        long long size = 0;
        for (NSString* path in childs) {
            NSString*_path = [filePath stringByAppendingPathComponent:path];
            long long _size = [self fileSizeAtPath:_path];
            size += _size;
        }
        
        return size;
    }
    return 0;
}

- (IBAction)longPressAction:(UILongPressGestureRecognizer *)sender {
    
    switch (sender.state) {
        case UIGestureRecognizerStateBegan:
            
            break;
        case UIGestureRecognizerStateCancelled:
            
            break;
        case UIGestureRecognizerStateEnded:
        {
            NSInteger tag = sender.view.tag;
            NSIndexPath* indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
            NSDictionary* info = [self.fileList objectAtIndex:indexPath.row];
            BOOL isDir = [[info objectForKey:@"isDir"] boolValue];
            if (!isDir) {
                
//                NSString* title = [info objectForKey:@"title"];
//                NSString* path = [[self.basePath stringByAppendingPathComponent:_childPath] stringByAppendingPathComponent:title];
//                
//                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"输入接收人工号" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"发送", nil];
//                alert.alertViewStyle = UIAlertViewStylePlainTextInput;
//                [alert show];
//                alert.userInfo = @{@"title":title,@"path":path};
                
            }
        }
            break;
        case UIGestureRecognizerStateFailed:
            
            break;
        case UIGestureRecognizerStateChanged:
            
            break;
            
        default:
            break;
    }
    
}

#pragma mark - UIAlertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        
//        YXAlertView* alert = (YXAlertView *) alertView;
//        UITextField* textField = [alertView textFieldAtIndex:0];
//        NSString* value = textField.text;
//        if (value.length > 0) {
//            value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//            if (value.length > 0) {
//                XMPPJID* jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",textField.text,[ConstantManager sharedInstance].XMPPDOMAIN]];
//                NSString* title = [alert.userInfo objectForKey:@"title"];
//                [[PublicUtils appDelegate] sendNewFile:[alert.userInfo objectForKey:@"path"] fileName:title toJID:jid type:@"file" uuid:[XMPPStream generateUUID] storeName:title messageType:@"file" videoURL:nil contactType:ContactTypeUser nickname:nil];
//            }
//        }
    }
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.fileList.count;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* identifier = @"fileList";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        
        UIView* line = [[UIView alloc] initWithFrame:CGRectMake(0,cell.frame.size.height - 1, cell.frame.size.width, 1)];
        line.backgroundColor = [UIColor lightGrayColor];
        line.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
        [cell.contentView addSubview:line];
        
        cell.detailTextLabel.textColor = [UIColor lightGrayColor];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.lineBreakMode = NSLineBreakByCharWrapping;
        cell.textLabel.numberOfLines = 2;
        cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
        
        UILongPressGestureRecognizer* longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
        [cell.contentView addGestureRecognizer:longPress];
    }
    
    cell.contentView.tag = indexPath.row;
    
    NSDictionary* info = [self.fileList objectAtIndex:indexPath.row];
    cell.textLabel.text = [info objectForKey:@"title"];
    
    BOOL isDir = [[info objectForKey:@"isDir"] boolValue];
    if (isDir) {
        cell.imageView.image = [UIImage imageNamed:@"FM_FODER.png"];
        cell.detailTextLabel.text = nil;

    }
    else
    {
        cell.imageView.image = [UIImage imageNamed:@"FM_FILE.png"];
    }
    
    if ([info objectForKey:@"size"]) {
        long long size = [[info objectForKey:@"size"] longLongValue];
        
        if (size > 1024 * 1024) {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"size : %.2fMB",size/1024.0/1024.0];
            
        }
        else if (size > 1024)
        {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"size : %.2fKB",size/1024.0];
            
        }
        else
        {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"size : %lldB",size];
            
        }
    }
    
    return cell;
}


- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary* info = [self.fileList objectAtIndex:indexPath.row];
    BOOL isDir = [[info objectForKey:@"isDir"] boolValue];
    if (isDir) {
        NSString* title = [info objectForKey:@"title"];
        
        if (_childPath) {
            self.childPath = [_childPath stringByAppendingPathComponent:title];
        }
        else
        {
            self.childPath = title;
        }
        
        [self resetFileList];
    }
    else
    {
        NSString* title = [info objectForKey:@"title"];
        
        if ([FMUtils isTxt:[title pathExtension]]) {
            
            NSString* path = [[self.basePath stringByAppendingPathComponent:_childPath] stringByAppendingPathComponent:title];
            FMTxtViewController* txt = [[FMTxtViewController alloc]initWithFilePath:path];
            [self.navigationController pushViewController:txt animated:YES];

        }
        else if ([[title pathExtension] isEqualToString:@"sqlite"]) {
            NSString* path = [[self.basePath stringByAppendingPathComponent:_childPath] stringByAppendingPathComponent:title];
            FMSQLiteViewController* sqlite = [[FMSQLiteViewController alloc] initWithFilePath:path];
            [self.navigationController pushViewController:sqlite animated:YES];
        }
        else if ([FMUtils isImage:[title pathExtension]]) {
            
            NSString* path = [self.basePath stringByAppendingPathComponent:_childPath];

            NSMutableArray* images = [NSMutableArray array];
            __block NSInteger index = 0;
            __block BOOL find = NO;

            [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil] enumerateObjectsUsingBlock:^(NSString* obj,NSUInteger idx, BOOL *stop){
                
                if ([FMUtils isImage:[obj pathExtension]]) {
                    [images addObject:obj];
                    
                    if ([obj isEqualToString:title]) {
                        find = YES;
                    }
                    
                    if (!find) {
                        index ++;
                    }
                }
            }];
            
            FMImageViewController* imageVC = [[FMImageViewController alloc]initWithImages:images basePath:path index:index];
            
            [self.navigationController pushViewController:imageVC animated:YES];
        }
        
    }
}

#pragma mark -


@end
